package kr.co.redcircle.service.oAuth.api.naver.me2day;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import kr.co.redcircle.service.oAuth.model.AbstractCommand;
import kr.co.redcircle.service.oAuth.model.ISNSCommandParameters;
import kr.co.redcircle.service.oAuth.model.ISNSResult;
import kr.co.redcircle.service.oAuth.model.SNSDefaultParameters;
import kr.co.redcircle.service.oAuth.model.SNSDefaultResult;
import net.sf.json.JSONObject;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Verb;

public class CommandPostThread extends AbstractCommand {

	@Override
	public ISNSResult invoke(ISNSCommandParameters paramCollection) {

		SNSDefaultResult result = new SNSDefaultResult();
		
		System.out.println("CommandPostThread.invoke.define value");
		SNSDefaultParameters params = (SNSDefaultParameters)paramCollection;
		String uid = (String) params.get("uid");
		String ukey = (String) params.get("ukey");
		String akey = (String) params.get("akey");
		String messageString  = (String) params.get("message");
		String utf8String = null;
		try {
			utf8String = URLEncoder.encode(messageString, "UTF-8");
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}   
		
		Verb type = getVerb(this.getKeyMethod().toLowerCase().trim());

		System.out.println("CommandPostThread.invoke.define request object : " + type);
		String targetInformation = String.format(this.getKeyVALUE(), akey, uid, ukey, utf8String);
		System.out.println("url : " + targetInformation);
		OAuthRequest req = new OAuthRequest(type, targetInformation);		
		Response resp = req.send();
		
		System.out.println("CommandPostThread.invoke.response");
		result.setCode(resp.getCode()+"");
		result.setBody(resp.getBody());
		result.setHeaders(resp.getHeaders());
		
		System.out.println("result.code : " + result.getCode());
		System.out.println("result.body : " + result.getBody());
  	
		JSONObject bodyObj = JSONObject.fromObject(result.getBody());

		return result;
		
	}
	
	private String toUnicode(String input){
		String str = "";
		char[] code = new char[100];
		int[] realCode = new int[100];
		
		for(int i=0; i < input.length(); i++) {
			code[i] = str.charAt(i);
			realCode[i] = (int)(code[i]);
		}
		
		for(int i=0; i < str.length();i++) {
			str += "\\u" + Integer.toHexString(realCode[i]).toUpperCase();
		}
		
		return str;
	}

	private String getUni(String input){
		
		String uniCodeStr = String.format(input);
		String[] rawUnicode = uniCodeStr.split("");
		
		int intVal = 0;
		char[] chVal = null;
		
		for(int i = 0; i < rawUnicode.length; i++ ) {
			chVal = rawUnicode[i].toCharArray();
			for(int j = 0; j < chVal.length; j++ ) {
				intVal = chVal[j];
				System.out.print(chVal[j]);
			}
		}
		
		return chVal.toString();
	}

}
